/*
 * Copyright 2009-2010 Nanjing RedOrange ltd (http://www.red-orange.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package redora.set;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import redora.api.Persistable;
import redora.api.PersistableSortedList;
import redora.api.SortedPersistable;
import redora.exceptions.ObjectNotFoundException;

import java.util.*;

public class PersistableSortedArrayList<E extends Persistable> extends
        PersistableArrayList<E> implements PersistableSortedList<E> {
    private boolean shuffled = false;
    private boolean asNtoM;

    public PersistableSortedArrayList(boolean asNtoM) {
        super();
        this.asNtoM = asNtoM;
    }

    public void move(@NotNull E e, int position) throws ObjectNotFoundException {
        if (position >= size()) {
            throw new IndexOutOfBoundsException("Position " + position + " is pointing outside our range " + size());
        }

        int old = indexOf(e);
        if (old == -1) {
            throw new ObjectNotFoundException(
                    "The to be moved object is not in our list");
        }

        if (position != old) { // not moving, do nothing
            shuffled = true;
            if (asNtoM) {
                //Sorting is maintained with the sort order in the list
                ArrayList<E> newList = new ArrayList<E>();
                int i = 0;
                for (E el : list) {
                    if (old > position && position == i++) { // moving up, go before
                        newList.add(e);
                    }
                    if (!e.equals(el)) {
                        newList.add(el);
                    }
                    if (old < position && position == i++) { // moving down, go
                        // after
                        newList.add(e);
                    }
                }
                list.clear();
                list.addAll(newList);
            } else {
                //Sorting is maintained in the persistable's sortOrder attribute
                int sort = 0;
                for (E reOrder : list) {
                    if (sort >= position) {
                        ((SortedPersistable) reOrder).setSortOrder(++sort);
                    } else {
                        ((SortedPersistable) reOrder).setSortOrder(sort++);
                    }
                    if (e.equals(reOrder)) {
                        ((SortedPersistable) reOrder).setSortOrder(position);
                        sort--;
                    }
                }
                Collections.sort((List<SortedPersistable>) list);
            }
        }
    }

    public boolean hasShuffled() {
        return shuffled;
    }

    /**
     * Adds given element to the bottom of the list. SortedPersistable elements
     * will get a (new) value for sortOrder overriding any old value.
     *
     * @param e element to be appended to this list
     * @return True if the list has grown one element
     */
    @Override
    public boolean add(@NotNull E e) {
        if (super.add(e)) {
            if (!asNtoM) {
                ((SortedPersistable)e).setSortOrder(size() - 1);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean addAll(@NotNull Collection<? extends E> c) {
        boolean retVal = false;
        for (E e : c) {
            if (add(e)) {
                retVal = true;
            }
        }
        return retVal;
    }

    @Override
    public boolean isDirty(@Nullable Set<Persistable> ignore) {
        return hasShuffled() || super.isDirty(ignore);
    }

    @Override
    public void clear() {
        super.clear();
        shuffled = false;
    }

    @Override
    public void reset() {
        super.reset();
        shuffled = false;
    }
}
